﻿package 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;	
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.filters.GlowFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.text.TextField;
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.materials.shadematerials.EnvMapMaterial;
	import org.papervision3d.materials.WireframeMaterial;
	import org.papervision3d.objects.primitives.Sphere;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;

	/*
	 * coded by moka 2009 / 06/ 22 
	 * name : moka's HDRLight
	 */
	
	public class Main extends Sprite 
	{		
		// 基本 PV3D 操作請參考 PV3D 基本教學
		private var scene:Scene3D = new Scene3D;
		private	var camera:Camera3D = new Camera3D;
		private	var viewport:Viewport3D = new Viewport3D(640, 480);
		private	var render:BasicRenderEngine = new BasicRenderEngine;
		private var bmp:Bitmap = new Bitmap(new BitmapData(640, 480, true, 0));
		private var bmpBuffer:BitmapData = bmp.bitmapData.clone();
		private var crystal:Sphere;
		
		
		// 貼圖的紋理
		[Embed(source = 'sceneMat.jpg')]
		private var EmbeddedImage:Class;
		private var image:Bitmap = new EmbeddedImage();

		public function Main():void 
		{		
			// 設定場景不變形
			stage.scaleMode = "noScale"; 
			addChild(bmp);
			
			crystal = scene.addChild(new Sphere(new WireframeMaterial(0xFFFFFF), 250, 4, 3)) as Sphere;
			crystal.rotationZ = 30;
			
			stage.addEventListener(Event.ENTER_FRAME, onProcess);
			// Moka's work 2009
			(addChild(new TextField()) as TextField).htmlText = "<font color='#FFFFFF'>Moka's work 2009</font>"; 
		}		
		
		private function onProcess(e:Event):void {
			crystal.rotationY = mouseX;
			
			render.renderScene(scene, camera, viewport);
			// 背景繪製
			bmpBuffer.draw(image.bitmapData);
			bmpBuffer.applyFilter(bmpBuffer, bmpBuffer.rect, new Point, new BlurFilter(8, 8, 3));
			bmpBuffer.draw(image.bitmapData, new Matrix, new ColorTransform(0.5, 0.5, 0.5, (1-Math.cos((crystal.rotationY+45)*4/180*Math.PI))/4),"add");
			// crystal水晶玻璃表面光源繪製			
			crystal.material = new EnvMapMaterial(new PointLight3D, bmpBuffer, image.bitmapData, 0xFFCC00);
			var glowBuffer:BitmapData = new BitmapData(640, 480, true, 0);
			glowBuffer.draw(viewport);
			glowBuffer.threshold(glowBuffer, glowBuffer.rect, new Point, "<", 0xFFAAAAAA);
			glowBuffer.applyFilter(glowBuffer, glowBuffer.rect, new Point, new GlowFilter(0xFFFFFF, 1, 50, 50, 5, 2));
			bmpBuffer.draw(viewport,new Matrix, new ColorTransform(1,1,1,0.8),"shader");
			bmpBuffer.draw(glowBuffer, new Matrix, new ColorTransform(0.5, 0.5, 0.5, 0.5), "add");
			
			bmp.bitmapData.draw(bmpBuffer);
		}   
	}	
}